package com.fiberhome.opticalbox.ui;

import java.util.ArrayList;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.content.ContentValues;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.BaseActivity;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.db.model.DBAttachInfo;
import com.fiberhome.opticalbox.net.NetConstant;
import com.fiberhome.opticalbox.net.NetManager.TcpErrorListener;
import com.fiberhome.opticalbox.net.NetManager.TcpListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.bean.Parameter.AttachInfo;
import com.fiberhome.opticalbox.net.bean.Parameter.MACInfo;
import com.fiberhome.opticalbox.net.utils.JsonUtil;
import com.fiberhome.opticalbox.utils.LogUtil;
import com.fiberhome.opticalbox.utils.NetworkUtil;
import com.fiberhome.opticalbox.view.third.xlist.XListView;

public class SurfCtrlActivity extends BaseActivity {

	private XListView listView;
	private List<SurfCtrlInfo> surfCtrlInfoList = new ArrayList<SurfCtrlInfo>();

	private ImageView imgSurfCtrl;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.ob_activity_surf_ctrl);
		super.onCreate(savedInstanceState);

		titleView.setTitle(R.string.ob_surf_ctrl_master);
		titleView.setBackground(R.drawable.ob_bg_title);
		titleView.addLeftDrawableMenu(this, R.drawable.ob_ico_back, 15, 25, onBackClickListener);

		imgSurfCtrl = (ImageView) findViewById(R.id.img_surf_ctrl);
		((AnimationDrawable) imgSurfCtrl.getDrawable()).start();

		listView = (XListView) findViewById(R.id.ob_listView);
		listView.setAdapter(adapter);
		listView.setPullRefreshEnable(false);
		listView.setPullLoadEnable(false);

		listView.setOnItemClickListener(onItemClickListener);

		registerChildTcpListener(tcpListener);
		registerChildTcpErrorListener(tcpErrorListener);
	}

	@Override protected void onResume() {
		super.onResume();
		request1AttachInfo();
	}

	private void request1AttachInfo() {
		netManager.sendTcp(JsonUtil.get_GET_ATTACH_INFO());
	}

	private void request2AttachDevice() {
		netManager.sendTcp(JsonUtil.get_GET_ATTACH_DEVICE_RIGHT(""));
	}

	private TcpListener tcpListener = new TcpListener() {
		@Override public void onReceive(String cmdType, Parameter param) {
			if (NetConstant.GET_ATTACH_INFO.equals(cmdType)) {
				surfCtrlInfoList.clear();
				if (param.AttachInfoList != null && param.AttachInfoList.size() > 0) {
					surfCtrlInfoList.addAll(SurfCtrlInfo.convert(param.AttachInfoList));
					request2AttachDevice();
				}
			} else if (NetConstant.GET_ATTACH_DEVICE_RIGHT.equals(cmdType)) {
				imgSurfCtrl.setVisibility(View.GONE);
				SurfCtrlInfo.merge(surfCtrlInfoList, param.MACList);
				adapter.notifyDataSetChanged();
			}
		}
	};

	private TcpErrorListener tcpErrorListener = new TcpErrorListener() {
		@Override public void onError(String cmdType) {
			if (NetConstant.GET_ATTACH_INFO.equals(cmdType)) {
				imgSurfCtrl.setVisibility(View.GONE);
			} else if (NetConstant.GET_ATTACH_DEVICE_RIGHT.equals(cmdType)) {
				imgSurfCtrl.setVisibility(View.GONE);
			}

			showToast(NetworkUtil.isDisconnected(SurfCtrlActivity.this) ? R.string.ob_error_net : R.string.ob_error_request);
		}
	};

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			SurfCtrlInfo surfCtrlInfo = (SurfCtrlInfo) surfCtrlInfoList.get(position - 1);
			if (TextUtils.isEmpty(surfCtrlInfo.MAC)) {
				showToast(R.string.ob_fail_get_device_mac);
				return;
			}
			try {
				Bundle bundle = new Bundle();
				bundle.putString(C.bundle.mac, surfCtrlInfo.MAC);
				bundle.putString(C.bundle.hostName, surfCtrlInfo.HostName);
				if (!TextUtils.isEmpty(surfCtrlInfo.StartTime)) {
					bundle.putInt(C.bundle.startHour, Integer.valueOf(surfCtrlInfo.StartTime.split(":")[0]));
					bundle.putInt(C.bundle.endHour, Integer.valueOf(surfCtrlInfo.StartTime.split(":")[1]));
				}
				if (!TextUtils.isEmpty(surfCtrlInfo.EndTime)) {
					bundle.putInt(C.bundle.endHour, Integer.valueOf(surfCtrlInfo.EndTime.split(":")[0]));
					bundle.putInt(C.bundle.endMin, Integer.valueOf(surfCtrlInfo.EndTime.split(":")[1]));
				}
				if (!TextUtils.isEmpty(surfCtrlInfo.DaysOfWeek)) {
					bundle.putString(C.bundle.dayOfWeek, surfCtrlInfo.DaysOfWeek);
				}
				actionStart(SurfCtrlSettingsActivity.class, bundle);
			} catch (Exception e) {
				LogUtil.e("SurfCtrlActivity onItemClick() setting params error");
				actionStart(SurfCtrlSettingsActivity.class, C.bundle.mac, surfCtrlInfo.MAC, C.bundle.hostName, surfCtrlInfo.HostName);
			}
		}
	};

	private BaseAdapter adapter = new android.widget.BaseAdapter() {

		@Override public View getView(int position, View convertView, ViewGroup parent) {
			final SurfCtrlInfo surfCtrlInfo = (SurfCtrlInfo) getItem(position);
			View view = null;
			ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				view = LayoutInflater.from(SurfCtrlActivity.this).inflate(R.layout.ob_list_content_surf_ctrl, null);
				viewHolder.layLimit = view.findViewById(R.id.lay_limit);
				viewHolder.txName = (TextView) view.findViewById(R.id.tx_name);
				viewHolder.txMac = (TextView) view.findViewById(R.id.tx_mac);
				viewHolder.txLimitState = (TextView) view.findViewById(R.id.tx_limit_state);
				viewHolder.imgIcoDevice = (ImageView) view.findViewById(R.id.img_ico_device);
				viewHolder.imgNoLimit = (ImageView) view.findViewById(R.id.img_no_limit);
				viewHolder.imgLimit = (ImageView) view.findViewById(R.id.img_limit);
				view.setTag(viewHolder);
			} else {
				view = convertView;
				viewHolder = (ViewHolder) view.getTag();
			}
			viewHolder.imgIcoDevice.setTag(surfCtrlInfo.MAC);
			// viewHolder.layLimit.setVisibility(surfCtrlInfo.isLimit() ?
			// View.VISIBLE : View.GONE);
			// viewHolder.imgNoLimit.setVisibility(surfCtrlInfo.isLimit() ?
			// View.GONE : View.VISIBLE);

			viewHolder.layLimit.setVisibility(surfCtrlInfo.isLimit() ? View.VISIBLE : View.GONE);
			viewHolder.imgNoLimit.setVisibility(surfCtrlInfo.isLimit() ? View.GONE : View.VISIBLE);

			String nickName = surfCtrlInfo.getNickName();
			if (TextUtils.isEmpty(nickName)) {
				nickName = TextUtils.isEmpty(surfCtrlInfo.HostName) ? getString(R.string.ob_device_unknown) : surfCtrlInfo.HostName;
			}
			viewHolder.txName.setText(nickName);
			viewHolder.txMac.setText(surfCtrlInfo.MAC);
			// String limitInfo = dealLimitTime(surfCtrlInfo);
			// viewHolder.imgLimit.setImageResource(!TextUtils.isEmpty(limitInfo)
			// ? R.drawable.ob_time_limit : R.drawable.ob_time_limit_disable);
			// viewHolder.txLimitState.setText(!TextUtils.isEmpty(limitInfo) ?
			// R.string.ob_time_limit : R.string.ob_time_limit_disable);

			viewHolder.imgLimit.setImageResource(R.drawable.ob_time_limit);
			viewHolder.txLimitState.setText(R.string.ob_time_limit);

			return view;
		}

		// private String dealLimitTime(SurfCtrlInfo surfCtrlInfo) {
		// String dot = getString(R.string.ob_dot);
		// String[] day =
		// getResources().getStringArray(R.array.ob_surf_ctrl_day);
		// String result = "";
		// if (!TextUtils.isEmpty(surfCtrlInfo.DaysOfWeek)) {
		// if ("1111111".equals(surfCtrlInfo.DaysOfWeek)) {
		// result = getString(R.string.ob_day_0);
		// } else if ("0000000".equals(surfCtrlInfo.DaysOfWeek)) {
		//
		// } else {
		// result = getString(R.string.ob_week_0);
		// byte[] daysInfo = surfCtrlInfo.DaysOfWeek.getBytes();
		// if (daysInfo != null && daysInfo.length > 0) {
		// for (int i = 0; i < daysInfo.length; i++) {
		// if ('1' == daysInfo[i]) {
		// result += day[i] + dot;
		// }
		// }
		// result = result.substring(0, result.length() - dot.length());
		// }
		// }
		//
		// }
		//
		// if (!TextUtils.isEmpty(result) &&
		// !TextUtils.isEmpty(surfCtrlInfo.StartTime) &&
		// !TextUtils.isEmpty(surfCtrlInfo.EndTime)) {
		// String StartTime = dealTimeInfo(surfCtrlInfo.StartTime);
		// String EndTime = dealTimeInfo(surfCtrlInfo.EndTime);
		// result += " " + StartTime + "-" + EndTime;
		// }
		// return result;
		// }
		// private String dealTimeInfo(String time) {
		// try {
		// int hour = Integer.parseInt(time.split(":")[0]);
		// int min = Integer.parseInt(time.split(":")[1]);
		// String strHour = hour < 10 ? "0" + hour : "" + hour;
		// String strMin = min < 10 ? "0" + min : "" + min;
		// return strHour + ":" + strMin;
		// } catch (Exception e) {
		// LogUtil.e("SurfCtrlActivity dealTimeInfo() deal fail");
		// return "";
		// }
		// }

		class ViewHolder {
			View layLimit;
			TextView txName;
			TextView txMac;
			// TextView txTimeLimit;
			ImageView imgIcoDevice;
			ImageView imgNoLimit;
			TextView txLimitState;
			ImageView imgLimit;
		}

		@Override public int getCount() {
			return surfCtrlInfoList.size();
		}

		@Override public Object getItem(int position) {
			return surfCtrlInfoList.get(position);
		}

		@Override public long getItemId(int position) {
			return position;
		}
	};

	/** surf ctrl adapter model */
	public static class SurfCtrlInfo {
		public String MAC;
		public String DaysOfWeek;
		public String StartTime;
		public String EndTime;
		public String HostName;
		public String InternetAccessRight;

		public SurfCtrlInfo(String MAC, String HostName) {
			this.MAC = MAC;
			this.HostName = HostName;
		}

		public void setCtrlInfo(String DaysOfWeek, String StartTime, String EndTime, String InternetAccessRight) {
			this.DaysOfWeek = DaysOfWeek;
			this.StartTime = StartTime;
			this.EndTime = EndTime;
			this.InternetAccessRight = InternetAccessRight;
		}

		public String getNickName() {
			List<DBAttachInfo> mDBAttachInfoList = DataSupport.where("mac = ?", MAC).find(DBAttachInfo.class);
			if (mDBAttachInfoList != null && mDBAttachInfoList.size() > 0) {
				DBAttachInfo mDBAttachInfo = mDBAttachInfoList.get(0);
				return mDBAttachInfo.getNickname();
			}
			return "";
		}

		public void saveNickName(String nickname) {
			List<DBAttachInfo> mDBAttachInfoList = DataSupport.where("mac = ?", MAC).find(DBAttachInfo.class);
			if (mDBAttachInfoList != null && mDBAttachInfoList.size() > 0) {
				DBAttachInfo mDBAttachInfo = mDBAttachInfoList.get(0);
				ContentValues values = new ContentValues();
				values.put("nickname", nickname);
				DataSupport.update(DBAttachInfo.class, values, mDBAttachInfo.getId());
			} else {
				DBAttachInfo mDBAttachInfo = new DBAttachInfo();
				mDBAttachInfo.setMac(MAC);
				mDBAttachInfo.setNickname(nickname);
				mDBAttachInfo.save();
			}
		}

		public boolean isLimit() {
			return "ON".equals(InternetAccessRight);
		}

		public static List<SurfCtrlInfo> convert(List<AttachInfo> MACInfoList) {
			List<SurfCtrlInfo> sciList = new ArrayList<SurfCtrlActivity.SurfCtrlInfo>();
			if (MACInfoList != null && MACInfoList.size() > 0) {
				for (AttachInfo attachInfo : MACInfoList) {
					if (!TextUtils.isEmpty(attachInfo.MAC)) {
						sciList.add(new SurfCtrlInfo(attachInfo.MAC, attachInfo.HostName));
					}
				}
			}
			return sciList;
		}

		public static List<SurfCtrlInfo> merge(List<SurfCtrlInfo> master, List<MACInfo> MACInfoList) {
			if (master != null && master.size() > 0) {
				if (MACInfoList != null && MACInfoList.size() > 0) {
					for (SurfCtrlInfo sci : master) {
						for (MACInfo macInfo : MACInfoList) {
							if (sci.MAC.equals(macInfo.MAC)) {
								sci.setCtrlInfo(macInfo.DaysOfWeek, macInfo.StartTime, macInfo.EndTime, macInfo.InternetAccessRight);
								break;
							}
						}
					}
				}
			}
			return master;
		}
	}

}